package com.zcsy.manage.web.tools;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;
import com.thoughtworks.xstream.io.xml.XppDriver;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.SignUtil;
import com.zcsy.manage.model.pay.weixin.PayOrderRequest;
import com.zcsy.manage.model.pay.weixin.PayOrderResponse;
import com.zcsy.manage.model.pay.weixin.PayOrderResultRequest;
import com.zcsy.manage.model.pay.weixin.PayOrderResultResponse;
import com.zcsy.manage.web.mall.ShopcartController;

/**
 * 微信支付工具类
 * @Title: WXPayUtils.java
 * @Package： com.zcsy.manage.web.tools 
 * @Description: 
 * @author hubing
 * @Copyright: 2016 武汉恒数利通软件有限公司 All rights reserved.
 * @date 2016年8月7日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
public class WXPayUtils {
    private static final Log logger = LogFactory.getLog(WXPayUtils.class);
    
    /**
     * 生成微信支付下单请求xml
     * @Method: createWeixinPayOrder
     * @param request
     * @author hubing
     * @date 2016年8月7日
     */
    public static String createWeixinPayRequset(PayOrderRequest request) {
        request.setAppid(Constants.APPID);
        request.setMch_id(Constants.MCH_ID);
        request.setTrade_type("NATIVE");//
        
        request.setSign(SignUtil.createSign(request));
        XStream xStream = new XStream(new XppDriver(new XmlFriendlyNameCoder("_-", "_"))); 
        xStream.alias("xml", PayOrderRequest.class);//根元素名需要是xml
        return xStream.toXML(request);
    }
    
    /**
     * 请求下单接口，同时返回结果
     * @Method: httpOrder
     * @param request 请求数据，xml格式
     * @author hubing
     * @date 2016年8月7日
     */
    public static String getSubmitOrderResponse(String request) {
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) new URL(Constants.WEIXIN_INTERFACE).openConnection();
            //加入数据  
            conn.setRequestMethod("POST"); 
            conn.setDoInput(true);
            conn.setDoOutput(true);  
            conn.setUseCaches(false);
              
            BufferedOutputStream buffOutStr = new BufferedOutputStream(conn.getOutputStream());  
            buffOutStr.write(request.getBytes());
            buffOutStr.flush();  
            buffOutStr.close();  
              
            //获取输入流  
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
              
            String line = null;  
            StringBuffer sb = new StringBuffer();  
            while((line = reader.readLine())!= null){  
                sb.append(new String(line.getBytes(), "UTF-8"));  
            }  
            
            XStream xStream = new XStream(new XppDriver(new XmlFriendlyNameCoder("_-", "_")));//说明3(见文末)
            // 将请求返回的内容通过xStream转换为UnifiedOrderRespose对象
            xStream.alias("xml", PayOrderResponse.class);
            PayOrderResponse respnse = (PayOrderResponse) xStream.fromXML(sb.toString());
            
            // 根据微信文档return_code 和result_code都为SUCCESS的时候才会返回code_url
            if(null!=respnse 
                    && "SUCCESS".equals(respnse.getReturn_code()) 
                    && "SUCCESS".equals(respnse.getResult_code())){
                return respnse.getCode_url();
            }else{
                return respnse.getReturn_msg();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        if(null != conn) {
//            conn.disconnect();
//        }
        return null;

    }
    
    /**
     * 支付结果接口数据
     * @Method: createWXPayResultRequest
     * @param request
     * @author hubing
     * @date 2016年8月7日
     */
    public static String createWXPayResultRequest(PayOrderResultRequest request) {
        request.setAppid(Constants.APPID);
        request.setMch_id(Constants.MCH_ID);
        request.setNonce_str(UniqueNumberUtils.get16UniqueNumber());
        
        request.setSign(SignUtil.createResultSign(request));
        XStream xStream = new XStream(new XppDriver(new XmlFriendlyNameCoder("_-", "_"))); 
        xStream.alias("xml", PayOrderResultRequest.class);//根元素名需要是xml
        return xStream.toXML(request);
    }
    
    /**
     * 支付结果查询返回数据
     * @Method: getPayResult
     * @param request
     * @author hubing
     * @date 2016年8月7日
     */
    public static PayOrderResultResponse getPayResult(String request){
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) new URL(Constants.WEIXIN_RESULT).openConnection();
            //加入数据  
            conn.setRequestMethod("POST"); 
            conn.setDoInput(true);
            conn.setDoOutput(true);  
            conn.setUseCaches(false);
              
            BufferedOutputStream buffOutStr = new BufferedOutputStream(conn.getOutputStream());  
            buffOutStr.write(request.getBytes());
            buffOutStr.flush();  
            buffOutStr.close();  
              
            //获取输入流  
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
              
            String line = null;  
            StringBuffer sb = new StringBuffer();  
            while((line = reader.readLine())!= null){  
                sb.append(new String(line.getBytes(), "UTF-8"));  
            }  
            logger.info("pay result xml ==== " + sb.toString());
            XStream xStream = new XStream(new XppDriver(new XmlFriendlyNameCoder("_-", "_")));//说明3(见文末)
            // 将请求返回的内容通过xStream转换为UnifiedOrderRespose对象
            xStream.alias("xml", PayOrderResultResponse.class);
            PayOrderResultResponse response = (PayOrderResultResponse) xStream.fromXML(sb.toString());
            
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e);
            logger.info(e.getMessage());
            return null;
        }
    }
    

}
